const fs = require('fs')
const fileService = require('./file.service')
const userService = require('../user/user.service')
// @ts-ignore
const { APP_HOST, APP_PORT } = require('../../app/config')
const { AVATAR_PATH } = require('../../app/file-path')

class FileController {

  // 保存头像信息
  async saveAvatarInfo(ctx, next) {
    try {
      // 1.获取图像信息
      const { filename, mimetype, size } = ctx.req.file
      const { id } = ctx.user
      const avatarUrl = `${APP_HOST}:${APP_PORT}/file/avatar/${id}`
      // 2.将图像数据保存到数据库
      await fileService.saveAvatarInfo(filename, mimetype, size, id)
      const result = await userService.updateAvatar(id, avatarUrl)
      // 3.返回结果
      ctx.body = result
    } catch (error) {
      ctx.throw(500, error.sqlMessage || error || "更新头像失败")
    }
  }

  // 获取用户头像
  async avatarInfo(ctx, next) {
    try {
      // 1.获取参数
      const { userId } = ctx.params
      // 2.查询数据
      const result = await fileService.getAvatarByUserId(userId)
      // 3.返回头像
      ctx.response.set('content-type', result.mimetype)
      ctx.body = fs.createReadStream(`${AVATAR_PATH}/${result.filename}`)
    } catch (error) {
      ctx.throw(500, error.sqlMessage || error || "获取用户头像失败")
    }
  }

}

module.exports = new FileController()
